# coding=utf-8
import os
import configparser
from tools.httpdoer import Request
import tools.convert as convert
from jproperties import Properties
import tools.globalvar as globalvar
from webapp.config import Config

class initsysparam:
    def init_sysparam(self):
        request = Request("http://120.55.151.10:8080/api/param/query")
        request.method = "post"  # 调用 _set_method
        #request.timeout = 10  # 调用 _set_timeout
        request.path_params=None
        request.body = {"param": convert.to_json_string({"fixedcolumns": {"NAMELIKE":"pos."},"order": [{"name": "ID","desc":True}]}) }
        r = request.send(json=False)
        r_data=[] #[{"NAME":"pos.test.rrr","VALUE":'ererererer'},{'NAME':'pos.tr.ww','VALUE':'yyyyyy'}]
        sys_object={}
        if r.status_code == 200:
            if r.json:
                res=convert.to_dict(r.json)
                if res["code"] == 0:
                    r_data = res["data"]
        if len(r_data)>0:
            filename =Config.ROOT_PATH+os.sep+r"initconfig"+os.sep+"sysparams.properties"
            file_dir = os.path.split(filename)[0]
            if not os.path.isdir(file_dir):
                os.makedirs(file_dir)
            if os.path.exists(filename):
                os.remove(filename)
            p = Properties()
            for i in range(len(r_data)):
                #print(r_data[i]["NAME"])
                # cf = configparser.ConfigParser()
                # cf.read(filename, encoding="utf-8")
                # cf.add_section("sys_param")
                # cf.set("sys_param",str(r_data[i]["NAME"]),str(r_data[i]["VALUE"]))
                # cf.write(open(filename, 'w',encoding='UTF-8'))
                #os.mknod(filename)
                key=str(r_data[i]["NAME"]).replace('.','_')
                p.__setitem__(key,str(r_data[i]["VALUE"]))
                sys_object[key]=str(r_data[i]["VALUE"])
            p.save(filename) #保存文件
            #同时设置全局变量对象
            globalvar.set_sysparamsobject(sys_object)


if __name__ == "__main__":
    init=initsysparam()
    init.init_sysparam()

    filename = os.getcwd() + os.sep + r"initconfig" + os.sep + "sysparams.properties"
    p = Properties()
    props = p.load(open(filename.encode('utf-8')))
    print(props.nodes.__getitem__(0).__dict__['value'])